package com.dingreading.cloud.admin.service.impl;

import com.dingreading.cloud.admin.entity.CourseTrainVideoLog;
import com.dingreading.cloud.admin.entity.table.CourseTrainVideoLogTableDef;
import com.dingreading.cloud.admin.mapper.CourseTrainVideoLogMapper;
import com.dingreading.cloud.admin.service.CourseTrainVideoLogService;
import com.dingreading.cloud.common.util.QueryFiledUtil;
import com.mybatisflex.core.query.QueryCondition;
import com.mybatisflex.core.query.QueryWrapper;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 服务层实现。
 *
 * @author Administrator
 * @since 2025-11-20
 */
@Service
public class CourseTrainVideoLogServiceImpl extends BaseServiceImpl<CourseTrainVideoLogMapper, CourseTrainVideoLog, CourseTrainVideoLogTableDef> implements CourseTrainVideoLogService {

    @Override
    protected CourseTrainVideoLogTableDef getTable() {
        return CourseTrainVideoLogTableDef.courseTrainVideoLog;
    }

    @Override
    public Map<List<Object>, List<CourseTrainVideoLog>> getAllVideoLogs(List<String> staffUids, List<String> fileUids, String beginDate, String endDate) {
        QueryCondition condition = QueryCondition.createEmpty()
                .and(table.staffUid.in(staffUids))
                .and(table.fileUid.in(fileUids))
                .and(table.addTime.between(QueryFiledUtil.appendMin00(beginDate), QueryFiledUtil.appendMin24(endDate)));

        QueryWrapper wrapper = QueryWrapper.create()
                .where(condition)
                .orderBy(table.startTime.asc());

        List<CourseTrainVideoLog> courseTrainVideoLogs = getMapper().selectListByQuery(wrapper);
        if (CollectionUtils.isEmpty(courseTrainVideoLogs))
            return Collections.emptyMap();
        //  定义一个函数Function，该函数将元素对象映射到一个键的集合里
        Map<List<Object>, List<CourseTrainVideoLog>> groupingLogMap = new HashMap<>();
        Function<CourseTrainVideoLog, List<Object>> compositeKey = log ->
                Arrays.asList(
                        log.getCorpUid(), log.getStoreUid(), log.getStaffUid(),
                        log.getCourseTrainUid(), log.getFileUid()
                );
        // 多属性分组
        groupingLogMap = courseTrainVideoLogs.stream().collect(Collectors.groupingBy(compositeKey, LinkedHashMap::new, Collectors.toList()));
        return groupingLogMap;
    }
}
